document.addEventListener('DOMContentLoaded', function() {
  // 获取元素
  const container = document.getElementById('container')
  const overlay = document.getElementById('overlay')
  const title = document.getElementById('title')
  const searchBar = document.getElementById('searchBar')
  const searchIcon = document.getElementById('searchIcon')
  const searchInput = document.getElementById('searchInput')
  const setIcon = document.getElementById('setIcon')
  const drawer = document.getElementById('drawer')
  const closeIcon = document.getElementById('closeIcon')
  const searchSelect = document.getElementById('searchSelect')
  const menuList = document.getElementById('menuList')


  menuList.addEventListener('click', (event)=> {
    if (event.target.tagName === 'LI') {
      const activeItem = this.querySelector('.active');
      if (activeItem) {
        activeItem.classList.remove('active');
      }
      event.target.classList.add('active');
    }
  })



  let searchStr = 'https://baidu.com/s?wd='

  let search = window.localStorage.getItem('search')
  searchMate(search)

  // 打开抽屉
  setIcon.addEventListener('click', (event) => {
    event.stopPropagation()
    drawer.style.right = '0'
  })

  // 点击关闭按钮关闭右侧抽屉
  closeIcon.addEventListener('click', () => {
    closeDrawer()
  })

  // 点击页面其他地方关闭右侧抽屉
document.addEventListener('click', (event) => {
  if (!drawer.contains(event.target) && event.target !== setIcon) {
    closeDrawer()
  }
})

// 关闭右侧抽屉
function closeDrawer() {
  drawer.style.right = '-100%'
}


// 切换搜索引擎
searchSelect.addEventListener('change', () => {
  const selectedValue = searchSelect.value
  window.localStorage.setItem('search', selectedValue)
  searchMate(selectedValue)
})

// 匹配当前搜索引擎
function searchMate(value) {
  switch(value) {
    case 'baidu':
      searchStr = 'https://baidu.com/s?wd='
      title.style.backgroundImage = "url(./img/baidu.png)"
      searchInput.placeholder = '百度一下...'
      searchSelect.value = 'baidu'
      break
    case 'bing':
      searchStr = 'https://www.bing.com/search?q='
      title.style.backgroundImage = "url(./img/bing.png)"
      searchInput.placeholder = '必应搜索...'
      searchSelect.value = 'bing'
      break
    case 'google':
      searchStr = 'https://www.google.com/search?q='
      title.style.backgroundImage = "url(./img/google.png)"
      searchInput.placeholder = '谷歌搜索...'
      searchSelect.value = 'google'
      break
  }

}


  // 跳转搜索页面
  searchInput.addEventListener('keyup', (event) => {
    console.log(searchStr);
    if (event.key === 'Enter') {
      const inputValue = searchInput.value
      if (inputValue) {
        let searchUrl = `${searchStr}${encodeURIComponent(inputValue)}`
        searchInput.value = ''
        window.open(searchUrl, '_blank')
      }
    }
  })

})